package com.miya.demo.config;

import com.github.yitter.contract.IdGeneratorOptions;
import com.github.yitter.idgen.YitIdHelper;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * id生成器配置
 *
 * @author CaiXiaowei
 * @date 2022/10/11
 */
@Configuration
@ConfigurationProperties(prefix = "id-generator")
@Data
public class IdGeneratorConfig {

    /**
     * 机器码, 分布式集群可自动注册,保证全局唯一
     */
    private Integer workId;

    /**
     * 机器码位长，决定 WorkerId 的最大值，默认值6，取值范围 [1, 19]
     */
    private Integer workerIdBitLength;

    /**
     * 序列数位长，默认值6，取值范围 [3, 21]
     */
    private Integer seqBitLength;

    @PostConstruct
    public void init() {
        IdGeneratorOptions options = new IdGeneratorOptions(workId.shortValue());
        options.WorkerIdBitLength = workerIdBitLength.byteValue();
        options.SeqBitLength = seqBitLength.byteValue();
        YitIdHelper.setIdGenerator(options);
    }
}
